package com.alien.admin.modules.gitlab.rest;

import com.alien.admin.exception.BadRequestException;
import com.alien.admin.modules.deploy.domain.DpServer;

import com.alien.admin.modules.gitlab.service.GitlabService;
import com.alien.admin.modules.gitlab.service.dto.MergeBranch;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.gitlab4j.api.models.Branch;
import org.gitlab4j.api.models.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequiredArgsConstructor
@Api(tags = "gitlab控制层")
@RequestMapping("/api/gitlab")
public class GitLabController {

    @Autowired
    GitlabService gitlabService;

    @PostMapping(value = "/queryBranchList")
    @ApiOperation("获取代码的分支列表")
    @PreAuthorize("@el.check('dpServer:list')")
    public ResponseEntity<Object> queryBranchList(@Validated @RequestBody DpServer dpServer){
        try {
            List<Branch> branchList = gitlabService.queryBranchList(dpServer);
            return new ResponseEntity<>(branchList, HttpStatus.OK);
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    @PostMapping(value = "/queryTagList")
    @ApiOperation("获取代码的tag列表")
    @PreAuthorize("@el.check('dpServer:list')")
    public ResponseEntity<Object> queryTagList(@Validated @RequestBody DpServer dpServer){
        try {
            List<Tag> tagList = gitlabService.queryTagList(dpServer);
            return new ResponseEntity<>(tagList, HttpStatus.OK);
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }

    @PostMapping(value = "/mergeBranch")
    @ApiOperation("合并代码")
    @PreAuthorize("@el.check('dpServer:list')")
    public ResponseEntity<Object> mergeBranch(@Validated @RequestBody MergeBranch mergeBranch){
        try {
            gitlabService.mergeBranch(mergeBranch);
            return new ResponseEntity<>("success", HttpStatus.OK);
        } catch (Exception e) {
            throw new BadRequestException(e.getMessage());
        }
    }
}
